package com.jrx.anytxn.param.service.system.impl;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.InternetUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.service.system.ISequenceNumberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class SequenceNumberServiceImpl implements ISequenceNumberService {
    private static final Logger logger = LoggerFactory.getLogger(SequenceNumberServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;

    @Override
    public String generateRefNo(Integer length) {
        StringBuilder sb = new StringBuilder();
        sb.append(DateUtils.format(DateUtils.now(), "yyMMddHHmmssSSS"));
        String ip = null;
        try {
            ip = InternetUtils.getLocalIp();
        } catch (Exception e) {
            logger.error("获取ip出错", e);
        }
        ip = StringUtils.right(ip, 2);
        if (StringUtils.isBlank(ip)) {
            ip = SeqUtils.getRandomNumber(2);
        }
        if (ip.length() < 2) {
            ip = StringUtils.getLengthStr(ip, 2, '0');
        }
        sb.append(ip);
        String seq = null;
        try {
            Long id = segmentService.getId(Constant.SEQUENCE_NUMBER);
            seq = id.toString();
        } catch (SegmentException e) {
            logger.error("获取序列出错", e);
            seq = SeqUtils.getRandomNumber(length - 17);
        }
        if (seq.length() < length - 17) {
            seq = StringUtils.getLengthStr(seq, length - 17, '0');
        }
        seq = StringUtils.right(seq, length - 17);
        sb.append(seq);

        return sb.toString();
    }

}
